from django.shortcuts import render, reverse
import logging

# 注意，下面的“django”字符串摘自“setting.py”中LOGGING对应的loggers所属的value值。换句话说，就是这个字符串必须在setting.py中定义！
# name为settings中loggers里面对应的名字
logger = logging.getLogger(name="django")

# Create your views here.

# from django.views.decorators.cache import cache_page
# 参数cache与全站缓存CACHE_MIDDLEWARE_ALIAS相同
# 参数key_prefix与全站缓存CACHE_MIDDLEWARE_KEY_PREFIX相同
# @cache_page(timeout=10, cache='default', key_prefix='xxx')

import datetime


# 必须定义一个request形参，request相当于我们自定义框架时的environ参数
def index(request):
    now = datetime.datetime.now()
    # print(now)
    ctime = now.strftime("%Y-%m-%d %X")
    return render(request, "app01/index.html", {"ctime": ctime})
    # render会读取templates目录下的index.html文件的内容并且用字典中的ctime的值替换模版中的{{ ctime }}

    # 我们在代码中写入日志
    # raise
    # logger.debug("这是第一条debug日志")
    # logger.info("这是第一条info日志")
    # logger.warning("这是第一条WARNING日志")
    # logger.error("这是第一条error日志")
    # logger.critical("这是第一条critical日志")
    # return HttpResponse(reverse('app01:index'))


# from django.shortcuts import render, HttpResponse
# from app01 import models
# def add_book(request):
#     book = models.Book(title="菜鸟教程", price=300, publish="菜鸟出版社", pub_date="2008-08-08")
#     book.save()
#     return HttpResponse(['<h1>数据添加成功</h1>'.encode('utf-8'),])

# from django.shortcuts import render,HttpResponse
# from app01 import models
# def add_book(request):
#     books = models.Book.objects.create(title="如来神掌",price=200,publish="功夫出版社",pub_date="2010-10-10")
#     print(books, type(books)) # Book object (18)
#     return HttpResponse("<p>数据添加成功！</p>")

# from django.shortcuts import render,HttpResponse
# from app01 import models
# def add_book(request):
#     books = models.Book.objects.all()
#     # for i in books:
#     #     print(i.title)
#     print(books,type(books)) # QuerySet类型，类似于list，访问 url 时数据显示在命令行窗口中。
#     return HttpResponse("<p>查找成功！</p>")


# from django.shortcuts import render,HttpResponse
# from app01 import models
# def add_book(request):
#     books = models.Book.objects.filter(pk=5)
#     print(books)
#     print("//////////////////////////////////////")
#     books = models.Book.objects.filter(publish='出版社', price=300)
#     print(books, type(books))  # QuerySet类型，类似于list。
#     return HttpResponse("<p>查找成功！</p>")

# from django.shortcuts import HttpResponse
# from app01 import models
# def add_book(request):
#     books = models.Book.objects.exclude(pk=5)
#     print(books)
#     print("//////////////////////////////////////")
#     books = models.Book.objects.exclude(publish='出版社', price=300)
#     print(books, type(books))  # QuerySet类型，类似于list。
#     return HttpResponse("<p>查找成功！</p>")

# from django.shortcuts import HttpResponse
# from app01 import models
# def add_book(request):
#     # books = models.Book.objects.get(pk=1)
#     books = models.Book.objects.get(pk=18)  # 报错，没有符合条件的对象
#     # books = models.Book.objects.get(price=200)  # 报错，符合条件的对象超过一个
#     print(books, type(books))  # 模型类的对象
#     return HttpResponse("<p>查找成功！</p>")

# from django.shortcuts import HttpResponse
# from app01 import models
# def add_book(request):
#     books = models.Book.objects.order_by("price") # 查询所有，按照价格升序排列
#     # books = models.Book.objects.order_by("-price") # 查询所有，按照价格降序排列
#     # return HttpResponse("<p>查找成功！</p>")
#     return HttpResponse(books)

# from django.shortcuts import HttpResponse
# from app01 import models
# def add_book(request):
#     # 按照价格升序排列：降序再反转
#     books = models.Book.objects.order_by("-price").reverse()
#     return HttpResponse(books)

# from django.shortcuts import HttpResponse
# from app01 import models
# def add_book(request):
#     books = models.Book.objects.count() # 查询所有数据的数量
#     # books = models.Book.objects.filter(price=200).count() # 查询符合条件数据的数量
#     return HttpResponse(books)

# from django.shortcuts import HttpResponse
# from app01 import models
# def add_book(request):
#     books = models.Book.objects.first() # 返回所有数据的第一条数据
#     return HttpResponse(books)


# from django.shortcuts import HttpResponse
# from app01 import models
# def add_book(request):
#     books = models.Book.objects.last() # 返回所有数据的最后一条数据
#     return HttpResponse(books)

# from django.shortcuts import HttpResponse
# from app01 import models
# def add_book(request):
#     # 查询成功
#     books = models.Book.objects.exists()
#     # 报错，判断的数据类型只能为QuerySet类型数据，不能为整型
#     # books = models.Book.objects.count().exists()
#     # 报错，判断的数据类型只能为QuerySet类型数据，不能为模型类对象
#     # books = models.Book.objects.first().exists()
#     return HttpResponse(books)

# from django.shortcuts import HttpResponse
# from app01 import models
# def add_book(request):
#     # 查询所有的id字段和price字段的数据
#     books = models.Book.objects.values("pk","price")
#     print(books[0]["price"],type(books)) # 得到的是第一条记录的price字段的数据
#     return HttpResponse(books)

# from django.shortcuts import HttpResponse
# from app01 import models
# def add_book(request):
#     # 查询所有的price字段和publish字段的数据
#     books = models.Book.objects.values_list("price","publish")
#     print(books)
#     print(books[0][0],type(books)) # 得到的是第一条记录的price字段的数据
#     print(books[1][0],type(books)) # 得到的是第二条记录的price字段的数据
#     return HttpResponse(books)

# from django.shortcuts import HttpResponse
# from app01 import models
# def add_book(request):
#     # 查询一共有多少个出版社
#     books = models.Book.objects.values_list("publish").distinct()
#     # 对模型类的对象去重没有意义，因为每个对象都是一个不一样的存在。
#     # books = models.Book.objects.distinct()
#     return HttpResponse(books)

# from django.shortcuts import HttpResponse
# from app01 import models
# def add_book(request):
#     books = models.Book.objects.filter(pk=42).first().delete()
#     books = models.Book.objects.filter(pk__in=[5, 10]).delete()
#     return HttpResponse(books)

# from django.shortcuts import HttpResponse
# from app01 import models
# def add_book(request):
#     books = models.Book.objects.filter(pk__in=[1,8]).update(price=888)
#     return HttpResponse(books)

# from django.shortcuts import HttpResponse
# from app01 import models
# def add_book(request):
#     #  获取出版社对象
#     pub_obj = models.Publish.objects.filter(pk=1).first()
#     #  给书籍的出版社属性publish传出版社对象
#     book = models.Book.objects.create(title="菜鸟教程", price=200, pub_date="2010-10-10", publish=pub_obj)
#     print(book, type(book))
#     return HttpResponse(book)

# from django.shortcuts import HttpResponse
# from app01 import models
# def add_book(request):
#     #  获取出版社对象
#     pub_obj = models.Publish.objects.filter(pk=1).first()
#     #  获取出版社对象的id
#     pk = pub_obj.pk
#     #  给书籍的关联出版社字段 publish_id 传出版社对象的id
#     book = models.Book.objects.create(title="冲灵剑法", price=100, pub_date="2004-04-04", publish_id=pk)
#     print(book, type(book))
#     return HttpResponse(book)

# from django.shortcuts import HttpResponse
# from app01 import models
# def add_book(request):
#     #  获取作者对象
#     chong = models.Author.objects.filter(name="令狐冲").first()
#     ying = models.Author.objects.filter(name="任盈盈").first()
#     #  获取书籍对象
#     book = models.Book.objects.filter(title="菜鸟教程").first()
#     #  给书籍对象的 authors 属性用 add 方法传作者对象
#     book.authors.add(chong, ying)
#     return HttpResponse(book)


# from django.shortcuts import HttpResponse
# from app01 import models
# def add_book(request):
#     #  获取作者对象
#     chong = models.Author.objects.filter(name="令狐冲").first()
#     #  获取作者对象的id
#     pk = chong.pk
#     #  获取书籍对象
#     book = models.Book.objects.filter(title="冲灵剑法").first()
#     #  给书籍对象的 authors 属性用 add 方法传作者对象的id
#     book.authors.add(pk)
#     return HttpResponse(book)

# from django.shortcuts import HttpResponse
# from app01 import models
# def add_book(request):
#     book_obj = models.Book.objects.get(id=1)
#     author_list = models.Author.objects.filter(id__gt=2)
#     book_obj.authors.add(*author_list)  # 将 id 大于2的作者对象添加到这本书的作者集合中
#     # 方式二：传对象 id
#     book_obj.authors.add(*[1,3]) # 将 id=1 和 id=3 的作者对象添加到这本书的作者集合中
#     return HttpResponse("ok")


# from django.shortcuts import HttpResponse
# from app01 import models
# from django.db.models import Avg, Max, Min, Count, Sum  # 引入函数
# def add_book(request):
#     res = models.Book.objects.aggregate(Avg("price"))
#     print(res, type(res))
#     return HttpResponse('ok')


# from django.shortcuts import HttpResponse
# from app01 import models
# from django.db.models import Avg, Max, Min, Count, Sum  # 引入函数
# def add_book(request):
#     res = models.Book.objects.aggregate(c=Count("id"),max=Max("price"),min=Min("price"))    # 别名
#     print(res, type(res))
#     return HttpResponse("ok")

# from django.shortcuts import HttpResponse
# from app01 import models
# from django.db.models import Avg, Max, Min, Count, Sum  # 引入函数
# def add_book(request):
#     res = models.Publish.objects.values("name").annotate(in_price = Min("book__price"))
#     print(res)
#     return HttpResponse("ok")

# from django.shortcuts import HttpResponse
# from app01 import models
# from django.db.models import Avg, Max, Min, Count, Sum  # 引入函数
# def add_book(request):
#     res = models.Book.objects.annotate(c = Count("authors__name")).values("title", "c")
#     print(res)
#     return HttpResponse("ok")

# from django.shortcuts import HttpResponse
# from app01 import models
# from django.db.models import Avg, Max, Min, Count, Sum  # 引入函数
# def add_book(request):
#     res = models.Book.objects.filter(title__startswith="菜").annotate(c=Count("authors__name")).values("title", "c")
#     print(res)
#     return HttpResponse("ok")

# from django.shortcuts import HttpResponse
# from app01 import models
# from django.db.models import Avg, Max, Min, Count, Sum  # 引入函数
# def add_book(request):
#     res = models.Book.objects.annotate(c=Count("authors__name")).filter(c__gt=0).values("title", "c")
#     print(res)
#     return HttpResponse("ok")


# from django.shortcuts import HttpResponse
# from django.db.models import F
# from app01 import models
# def add_book(request):
#     book = models.Emp.objects.filter(salary__gt=F("age")).values("name","age")
#     print(book)
#     return HttpResponse("ok")

# from django.shortcuts import HttpResponse
# from django.db.models import F
# from app01 import models
# def add_book(request):
#     res = models.Book.objects.update(price=F("price")+100)
#     print(res)
#     return HttpResponse("ok")


# from django.shortcuts import HttpResponse
# from django.db.models import Q
# from app01 import models
# def add_book(request):
#     res = models.Book.objects.filter(Q(price__gt=350)|Q(title__startswith="菜")).values("title","price")
#     print(res)
#     return HttpResponse("ok")


# from django.shortcuts import HttpResponse
# from django.db.models import Q
# from app01 import models
# def add_book(request):
#     res = models.Book.objects.filter(Q(title__endswith="菜") | ~Q(Q(pub_date__year=2010) & Q(pub_date__month=10)))
#     print(res)
#     return HttpResponse("ok")

from django.shortcuts import HttpResponse
from django.db.models import Q
from app01 import models


def add_book(request):
    res = models.Book.objects.filter(Q(pub_date__year=2004) | Q(pub_date__year=1999), title__contains="菜")
    print(res)
    return HttpResponse("ok")


# # 重定向、响应
# from django.shortcuts import render, HttpResponse
# from django.views.decorators import csrf
# from app01.My_forms import EmpForm
# from app01 import models
# # create your views here.
# def add_emp(request):
#     if request.method == "GET":     #第一次请求get渲染输入标签给客户端
#         form = EmpForm()    #空的form,用来渲染页面的
#         return render(request, "app01/add_emp.html", {"form": form}, locals())
#     else:
#         form = EmpForm(request.POST)    #用传进来的数据构造对象
#         if form.is_valid(): #把构造的对象进行校验
#             # 校验成功
#             data = form.cleaned_data  #校验成功的值，会放在cleaned_data里，
#             # data.pop('salary')
#             print(data)
#             models.Emp.objects.create(**data)   #校验通过就写入数据库
#             return HttpResponse('校验ok')
#             # return render(request, ""app01/add_emp.html", {"form": form})
#         else:       #校验不通过
#             # 错误信息是一个HTML的ul标签囊括的
#             print(form.errors)    # 打印错误信息
#             # 错误信息是一个字典
#             print(form.errors.as_data())
#             clean_errors = form.errors.get("__all__")
#             print(2222, clean_errors)
#         return render(request, "app01/add_emp.html", {"form": form, "clean_errors": clean_errors}, locals()) #校验不通过还是渲染一个页面返回会用户.只不过这个页面渲染的已经不是一个空form对象,而是用户输入的信息对象


# 重定向、响应
from django.shortcuts import render, HttpResponse
from django.views.decorators import csrf
from app01.My_forms import EmpForm
from app01 import models


# create your views here.
def add_emp(request):
    if request.method == "GET":  # 第一次请求get渲染输入标签给客户端
        form = EmpForm()  # 空的form,用来渲染页面的
        return render(request, "app01/add_emp.html", {"form": form}, locals())
    else:
        form = EmpForm(request.POST)  # 用传进来的数据构造对象
        if form.is_valid():  # 把构造的对象进行校验
            # 校验成功
            data = form.cleaned_data  # 校验成功的值，会放在cleaned_data里
            print(data)
            data.pop('r_salary')
            print(data)
            models.Emp.objects.create(**data)  # 校验通过就写入数据库
            return HttpResponse('添加成功')
        else:  # 校验不通过
            # 错误信息是一个HTML的ul标签囊括的
            # print(form.errors)    # 打印错误信息
            # 错误信息是一个字典
            print(form.errors.as_data())
            clean_errors = form.errors.get("__all__")
            print(2222, clean_errors)
        return render(request, "app01/add_emp.html", {"form": form, "clean_errors": clean_errors},
                      locals())  # 校验不通过还是渲染一个页面返回会用户.只不过这个页面渲染的已经不是一个空form对象,而是用户输入的信息对象


def midd(request):
    print("midd视图")
    return HttpResponse("ok")


from django.core.mail import send_mail
from django.http import HttpResponse


def sendMail(request):
    send_mail(
        subject='邮件测试',
        message='test',
        from_email='open_falcon_666@163.com',  # 也可以从settings中获取，例如： settings.DEFAULT_FROM_EMAIL
        recipient_list=['tenpy22@gmail.com', 'liknt220@gmail.com', ],
        fail_silently=False
    )
    return HttpResponse('ok')

# from django.core.mail import send_mail
# from django.conf import settings
# def sendMail(request):
#     send_mail(
#         # 发送邮件的标题
#         '注册激活，谢谢使用！',
#         # 发送邮件的内容
#         'Here is the message.',
#         # 发送者
#         settings.DEFAULT_FROM_EMAIL,
#         # 接受者
#         ['liknt220@gmail.com',],
#         # 发送失败是否返回错误信息
#         fail_silently=False,
#     )
#     return HttpResponse('邮件发送成功')
